import http from './interface'
import store from '@/store/index.js'

const BASE_URL = 'https://mini.chi1jing.com'
/**
 * 将业务所有接口统一起来便于维护
 * 如果项目很大可以将 url 独立成文件，接口分成不同的模块
 * 
 */

// 单独导出(测试接口) import {execute} from '@/common/vmeitime-http/'

const request =  (data = {}) => {

		let resendRequestURL = data.url

		http.config.baseUrl = BASE_URL
		//设置请求前拦截器
		http.interceptor.request = (config) => {
			let token = store.getters.getToken
			config.header = {
				"token": token || '',
				'Content-Type': 'application/x-www-form-urlencoded'
			}
		}
		//设置请求结束后拦截器
		http.interceptor.response = async (response) => {
			const isRefreshToken = response.config.url.includes('refreshToken')
			if (response.data.resultCode === 401 && !isRefreshToken) {
				response = await refreshToken(response, resendRequestURL)
				return response
			}
			if (response.data.resultCode === 0) {
				// 请求状态成功返回请求数据
				return response.data
			} else {
				// 请求失败，显示信息
				uni.showToast({
					title: response.data.resultMsg,
					icon: 'none'
				})
				return Promise.reject(response.data)
			}
		}
		return http.request(data)
	}

module.exports = {
	request
}

// 刷新token并继续之前请求
async function refreshToken(response, resendRequestURL) {
	const userInfo = store.getters.getUserInfo
	const userToken = store.getters.getToken

	const res = await request({
		url: '/cj/web/refreshToken',
		method: 'POST',
		data: {
			data: JSON.stringify({
				openId: userInfo ? userInfo.openId : '',
				latestToken: userToken ? userToken : ''
			})
		}
	})
	// 存储token
	uni.setStorageSync('token', res.resultData.token)
	store.commit('setToken', res.resultData.token)

	// 继续之前的请求
	return resendRequest(response, resendRequestURL)
}

// 继续之前请求
async function resendRequest(response, resendRequestURL) {
	let config = response.config
	config.header.token = store.getters.getToken

	var postData = {
		url: resendRequestURL,
		data: config.data,
		method: config.method
	}
	const resold = request(postData)
	return resold
}
